﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Quaack
{
    public partial class BevestigAccount : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            // checken of er een userId is
            Guid userId;

            try
            {
                userId = new Guid(Request.Params["ID"]);
            }
            catch (Exception exception)
            {
                lblBevestigAccount.Text = (string)GetLocalResourceObject("FailureTextOnbekend.Text");
                return;
            }

            userId = new Guid(Request.Params["ID"]);
            MembershipUser user = Membership.GetUser(userId);

            // error message bij inloggen
            if (user == null)
            {
                Login1.FailureText = (string)GetLocalResourceObject("FailureTextOnbekend.Text");
            }
            if (user != null)
            {
                if (user.IsApproved)
                {
                    Login1.FailureText = (string)GetLocalResourceObject("FailureTextOnjuist.Text");
                }
                if (!user.IsApproved)
                {
                    Login1.FailureText = (string)GetLocalResourceObject("FailureTextNietActief.Text");
                }
            }

            // gebruiker activeren
            if (String.IsNullOrEmpty(Request.Params["ID"]))
            {
                // geen userId, dan error message
                lblBevestigAccount.Text = (string)GetLocalResourceObject("ErrorOnbekendeGebruiker.Text");
            }
            else
            {
                // er is een userId
                try
                {
                    // tijd van aanmaken van de account + 10 minnuten, daarna vervalt de mogelijkheid tot activatie
                    DateTime createDate = user.CreationDate.AddMinutes(10);
                    DateTime activationTime = DateTime.Now;

                    if (activationTime > createDate)
                    {
                        lblBevestigAccount.Text = (string)GetLocalResourceObject("Error10min.Text");
                        return;
                    }

                    // zet veld in de database op geactiveerd
                    user.IsApproved = true;

                    // zet veld in Quaack tabel op geactiveerd
                    string connectionString = ConfigurationManager.ConnectionStrings["QuaackSqlConnection"].ConnectionString;
                    var updateSql = "UPDATE [Quaack].[dbo].[profile] SET verificationpending = 1 WHERE username = '" + user + "'";

                    using (var myConnection = new SqlConnection(connectionString))
                    {
                        myConnection.Open();

                        var myCommand = new SqlCommand(updateSql, myConnection);

                        myCommand.ExecuteNonQuery();

                        myConnection.Close();
                    }

                    var emailQuery = "SELECT email FROM [Quaack].[dbo].[profile] WHERE username = '" + user + "'";
                    string userEmail;

                    using (var myConnection = new SqlConnection(connectionString))
                    {
                        myConnection.Open();

                        var myCommand = new SqlCommand(emailQuery, myConnection);

                        userEmail = myCommand.ExecuteScalar().ToString();

                        myConnection.Close();
                    }

                    // variabelen voor gegevens uitnodiger en uitgenodigde
                    string inviterName = string.Empty;
                    string inviterEmail = string.Empty;

                    var invitedByQuery = "SELECT invitedby FROM [Quaack].[dbo].[invitation] WHERE inviteduseremail = '" + userEmail + "'";
                    // check of gebruiker voorkomt
                    var invitedByCheckQuery = "SELECT COUNT(*) invitedby FROM [Quaack].[dbo].[invitation] WHERE inviteduseremail = '" + userEmail + "'";

                    using (var myConnection = new SqlConnection(connectionString))
                    {
                        var myCommandCheck = new SqlCommand(invitedByCheckQuery, myConnection);
                        
                        myConnection.Open();

                        var invitedByCheck = (Int32)myCommandCheck.ExecuteScalar();
                        myConnection.Close();

                        // als gebruiker voorkomt
                        if (invitedByCheck > 0)
                        {
                            var myCommand = new SqlCommand(invitedByQuery, myConnection);

                            myConnection.Open();
                            inviterName = myCommand.ExecuteScalar().ToString();

                            var queryCheckInviterEmail = "SELECT COUNT(*) email FROM [Quaack].[dbo].[profile] WHERE username = '" + inviterName + "'";
                            var inviterEmailQuery = "SELECT email FROM [Quaack].[dbo].[profile] WHERE username = '" + inviterName + "'";

                            myCommand = new SqlCommand(queryCheckInviterEmail, myConnection);
                            var checkInviterEmail = (Int32)myCommand.ExecuteScalar();
                            // als email bestaat
                            if (checkInviterEmail > 0)
                            {
                                myCommand = new SqlCommand(inviterEmailQuery, myConnection);
                                inviterEmail = myCommand.ExecuteScalar().ToString();
                            }

                            myConnection.Close();

                            if (!string.IsNullOrEmpty(inviterEmail))
                            {
                                string title = "Gebruiker heeft zich geregistreerd bij Quaack";
                                string body = string.Format("{0} heeft zich geregistreerd bij Quaack", user);
                                SendMailInvitation(inviterEmail, title, body);
                            }
                        }


                    }

                    // update gebruikersaccount
                    Membership.UpdateUser(user);

                    // Gebruiker is succesvol geactiveerd
                    lblBevestigAccount.Text = (string)GetLocalResourceObject("SuccesMessage.Text");
                }
                catch
                {
                    // Error
                    lblBevestigAccount.Text = (string)GetLocalResourceObject("ErrorOnbekend.Text");
                }
            }
        }
        //email functie voor versturen email als de uitgenodigde zich heeft geregistreerd
        private void SendMailInvitation(String emailAddress, String title, String body)
        {
            var mail = new MailMessage("quaackwebapp@gmail.com", emailAddress, title, body);
            mail.IsBodyHtml = true;

            var smtp = new SmtpClient("smtp.gmail.com");
            smtp.Credentials = new System.Net.NetworkCredential(
            "quaackwebapp@gmail.com", "quaack2013");
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
    }
}